<?php


namespace App\Http\Controllers\Forwarder;


use App\Http\Controllers\Controller;
use App\Models\Config;
use App\Models\Forwarder;
use App\Models\ForwarderLine;
use App\Models\ForwarderStat;
use App\Models\WorldCity;
use Illuminate\Http\Request;

class ForwarderLineController extends Controller
{

    public function selectData(Request $request){
        $serve = Config::getValue('serve');
        $cargo = Config::getValue('cargo');
        $forwarder = Forwarder::where('id', $request->user()->forwarder_id)->select('name','img')->first();
        return $this->response(compact('serve','cargo','forwarder'));
    }

    public function index(Request $request)
    {
        $query = ForwarderLine::where('forwarder_id', $request->user()->forwarder_id);
        if ($request->input('status')){
            $query->where('status', $request->input('status'));
        }
        $list = $query->get();
        return $this->response($list);
    }

    public function view($id, Request $request){
        $obj = ForwarderLine::where('forwarder_id', $request->user()->forwarder_id)->where('id',$id)->first();
        $obj->from_att = WorldCity::where('name_zh', $obj->from)->first();
        $obj->to_att = WorldCity::where('name_zh', $obj->to)->first();
        $obj->forwarder_stat = ForwarderStat::first();
        return $this->response($obj);
    }

    public function store(Request $request, ForwarderLine $obj)
    {
        $all = $request->all();
        $obj->fill($all);
        $obj->user_id = $request->user()->id;
        $obj->forwarder_id = $request->user()->forwarder_id;
        $obj->save();
        return $this->response($obj->id);
    }

    public function update($id, Request $request)
    {
        $obj = ForwarderLine::where('forwarder_id', $request->user()->forwarder_id)->where('id', $id)->first();
        $obj->update($request->all());
        return $this->response();
    }

    public function destroy($id)
    {
        $obj = ForwarderLine::find($id);
        $obj->delete();
        return $this->response();
    }
}
